package ao

import (
    "crypto/tls"
    "errors"
    "fmt"
    "gopkg.in/gomail.v2"
    "micro.verify.server/config"
    "micro.verify.server/database"
    "micro.verify.server/utils"
    "time"
)

const (
    REGISTRY_EMAIL_KEY = "micro_user_registry_email:%s"
)

func SendEmail(receiver string) error {
    code := utils.GetRandomString(8)
    em := gomail.NewMessage()

    // fcmafnencmiljaji
    em.SetHeader("From", config.GConf.Email.SendEmail, "micro-hotel")
    em.SetHeader("To", em.FormatAddress(receiver, "micro-hotel platform"))
    em.SetHeader("Subject", "welcome to registry micro-hotel platform")
    em.SetBody("text/html", "<h4>欢迎注册micro-hotel平台</h4><p>注册邮箱验证码："+ code +"</p>")

    d :=  gomail.NewDialer(config.GConf.Email.SendHost, config.GConf.Email.SendPort,config.GConf.Email.SendEmail,config.GConf.Email.SendPassword)
    d.TLSConfig = &tls.Config{
        InsecureSkipVerify: true,
    }
    if err := d.DialAndSend(em);err != nil {
        return err
    }

    // 将code 保存到redis中
    exist := database.GetRedis().SetNX(fmt.Sprintf(REGISTRY_EMAIL_KEY, receiver), code, 10*time.Minute).Val()
    if !exist {
        err := errors.New(fmt.Sprintf("邮箱验证码已发送至%s邮箱,请勿重复发送", receiver))
        return err
    }

    return nil
}

func VerifyEmailCode(receiverEmail, emailCode string) (bool, error) {
    result := database.GetRedis().Get(fmt.Sprintf(REGISTRY_EMAIL_KEY, receiverEmail))
    if result.Err() != nil {
        return false, result.Err()
    }
    if result.Val() != emailCode {
        return false, errors.New("code error")
    }

    return true, nil
}